package com.artisan.booteventbus.bus;

import com.artisan.booteventbus.dao.MessageRepository;
import com.artisan.booteventbus.domain.MessageEvent;
import com.artisan.booteventbus.domain.MessageSentEvent;

import com.artisan.booteventbus.service.MessageChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.scheduling.annotation.Async;

import java.util.List;

@Component
public class MessageEventProcessor implements EventHandler<MessageEvent> {

    private final EventBus eventBus;
    private final MessageRepository messageRepository;
    private final List<MessageChannel> channels;

    @Autowired
    public MessageEventProcessor(EventBus eventBus, MessageRepository messageRepository, List<MessageChannel> channels) {
        this.eventBus = eventBus;
        this.messageRepository = messageRepository;
        this.channels = channels;
    }

    /**
     * @param event
     * Asyn 请使用自定义线程池，这里仅仅是 为了演示异步
     */
    @Async
    @Override
    public void handle(MessageEvent event) {
        // 1. 消息持久化
        messageRepository.save(event);

        // 2. 通道路由
        MessageChannel channel = channels.stream()
                .filter(ch -> ch.supports(event))
                .findFirst()
                .orElseThrow();

        // 3. 异步发送
        channel.sendAsync(event)
                .thenRun(() -> eventBus.publish(new MessageSentEvent(event)));
    }

}
